<template>
  <el-container class="login-container">
    <el-main>
      <el-card class="login-card">
        <br />
        <h2 style="text-align: center; margin-bottom: 20px">用户登录</h2>
        <!-- 内容容器 -->
        <div class="login-content">
          <!-- 账号密码表单 -->
          <transition name="fade">
            <div v-show="activeType === 'account'" class="login-form">
              <el-form :model="accountForm" label-position="top">
                <el-form-item label="用户名">
                  <el-input
                    v-model="accountForm.userName"
                    placeholder="请输入用户名"
                  />
                </el-form-item>
                <el-form-item label="密码">
                  <el-input
                    v-model="accountForm.password"
                    type="password"
                    show-password
                    placeholder="请输入密码"
                  />
                </el-form-item>
                <!-- 添加记住我复选框 -->
                <el-form-item>
                  <div
                    style="
                      display: flex;
                      justify-content: space-between;
                      flex-direction: row;
                      align-items: center;
                      width: 100%;
                    "
                  >
                    <el-checkbox
                      v-model="accountForm.rememberMe"
                      label="记住我(30天内自动登录)"
                    />
                    <el-button disabled type="success" v-if="isVarify">
                      认证通过
                    </el-button>
                      <CaptchaComp v-else
                        v-model:isVarify="isVarify"
                        v-model:captchaBtn="captchaBtn"
                      />
                  </div>
                </el-form-item>

                <el-button
                  v-if="
                    isVarify && accountForm.userName && accountForm.password
                  "
                  type="success"
                  @click="submitAccountLogin"
                  style="width: 100%"
                  >登录</el-button
                >
                <el-button v-else type="info" style="width: 100%" disabled
                  >登录</el-button
                >
              </el-form>
            </div>
          </transition>

          <!-- 手机验证码表单 -->
          <transition name="fade">
            <div v-show="activeType === 'phone'" class="login-form">
              <el-form :model="phoneForm" label-position="top">
                <el-form-item label="手机号">
                  <el-input
                    v-model="phoneForm.phone"
                    placeholder="请输入手机号"
                  />
                </el-form-item>
                <el-form-item label="验证码">
                  <div
                    style="
                      display: flex;
                      width: 100%;
                      flex-direction: row;
                      justify-content: space-between;
                    "
                  >
                    <el-input
                      v-model="phoneForm.code"
                      placeholder="请输入验证码"
                      style="width: 60%"
                    />
                    <el-button @click="sendVerificationCode" plain
                      >发送验证码</el-button
                    >
                  </div>
                </el-form-item>
                <br />
                <el-button
                  type="primary"
                  @click="submitPhoneLogin"
                  style="width: 100%"
                  >登录</el-button
                >
              </el-form>
            </div>
          </transition>

          <!-- OAuth2 表单 -->
          <transition name="fade">
            <div
              v-show="activeType === 'oauth2'"
              class="login-form oauth2-content"
            >
              <br />
              <div
                class="oauth2-providers"
                style="display: flex; justify-content: space-around"
              >
                <el-button
                  class="oauth2-provider-button qq"
                  @click="loginWithOAuth2('qq')"
                ></el-button>

                <el-button
                  class="oauth2-provider-button wechat"
                  @click="loginWithOAuth2('wechat')"
                ></el-button>
              </div>
            </div>
          </transition>
        </div>
        <br />

        <!-- 固定图标切换区 -->
        <div class="login-type-switch">
          <el-tooltip content="账号密码登录" placement="top">
            <el-button
              circle
              :type="activeType === 'account' ? 'primary' : 'default'"
              @click="switchLoginType('account')"
            >
              <el-icon>
                <User />
              </el-icon>
            </el-button>
          </el-tooltip>

          <el-tooltip content="手机验证码登录" placement="top">
            <el-button
              circle
              :type="activeType === 'phone' ? 'primary' : 'default'"
              @click="switchLoginType('phone')"
            >
              <el-icon><Phone /></el-icon>
            </el-button>
          </el-tooltip>

          <el-tooltip content="OAuth2 登录" placement="top">
            <el-button
              circle
              :type="activeType === 'oauth2' ? 'primary' : 'default'"
              @click="switchLoginType('oauth2')"
            >
              <el-icon><Key /></el-icon>
            </el-button>
          </el-tooltip>
        </div>

        <!-- 其他链接 -->
        <div
          style="position: absolute; bottom: 46px; right: 35px; font-size: 14px"
        >
          <a
            @click="router.push('/register')"
            style="color: #409eff; text-decoration: none; margin-right: 10px"
            >立即注册</a
          >
          <a href="#" style="color: #409eff; text-decoration: none"
            >忘记密码？</a
          >
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import LoginView  from "@/api/Backend/LoginView";
import router from "@/router";
import axios from "axios";
// 导入Pinia状态管理
import { userInfo } from "@/stores/userinfo";
// 初始化状态管理实例
const isVarify = ref(false);
const userStore = userInfo();
const activeType = ref("account");
const captchaBtn = ref(null);
const triggerCaptcha = () => {
  console.log("triggerCaptcha");
  captchaBtn.value.$el.click();
};
const switchLoginType = (type) => {
  isVarify.value = false;
  activeType.value = type;
};

// 账号密码登录数据
const accountForm = ref({
  userName: "", // 注意：后端接收的是userName字段（首字母小写）
  password: "",
  rememberMe: false, // 添加记住我字段，默认不勾选
});

// 手机验证码登录数据
const phoneForm = ref({
  phone: "",
  code: "",
});

// 提交账号密码登录
const submitAccountLogin = async () => {
  try {
    // 调用状态管理的登录方法
    await userStore.login(accountForm.value);
    // 登录成功后跳转到用户界面->首页
    router.push("/");
  } catch (error) {
    // 统一错误处理
    alert(error.message || "登录失败，请重试");
  }
};

// 提交手机验证码登录
const submitPhoneLogin = async () => {
try {

   

    // 输入验证
    if (!phoneForm.value.phone) {
      alert("请输入手机号");
      return;
    }
    
    
    if (!phoneForm.value.code) {
      alert("请输入验证码");
      return;
    }
    
    
    // 验证手机号格式（与发送验证码时保持一致）
    const phonePattern = /^1[3-9]\d{9}$/;
    if (!phonePattern.test(phoneForm.value.phone)) {
      alert("请输入有效的手机号");
      return;
    }
    // 调用后端手机登录接口（假设接口接收phone和code参数）
      const phoneNumber= phoneForm.value.phone;
      const inputCode = phoneForm.value.code;
    const res = await axios.post(`api/sms/verify-sms-login?phoneNumber=${phoneNumber}&inputCode=${inputCode}`); 
    if(res.data.code==200){
      console.log(res);
     // 登录成功处理（复用账号密码登录的状态管理逻辑）
    await userStore.login(res.data.data); // 假设res.data包含用户信息和token// router.push("/");
      router.push("/");
    }else{
      alert(res.data.msg);
    }
  } catch (error) {
    // 统一错误处理（兼容后端自定义错误和网络异常）
    const errorMsg = 
      error.response?.data?.message || 
      error.message || 
      "手机验证码登录失败，请重试";
    alert(errorMsg);
  }
};

// 发送验证码
const sendVerificationCode = async() => {
  console.log(phoneForm.value.phone);

  if (!phoneForm.value.phone) {
    alert("请输入手机号");
    return;
  }
  
  // 验证手机号格式（简单示例，可根据实际需求调整）
  const phonePattern = /^1[3-9]\d{9}$/; // 中国大陆手机号格式
  if (!phonePattern.test(phoneForm.value.phone)) {
    alert("请输入有效的手机号");
    return;
  }
  
  try {
    const res = await LoginView.getTextMessage(phoneForm.value.phone);
    console.log('res:', res);
    if (res.code === 200) {
      alert("验证码已发送，请查收");
    } else {
      alert(res.message || "发送验证码失败");
    }
  } catch (error) {
    alert(error.message || "发送验证码失败，请重试");
  }
};

// 第三方登录
const loginWithOAuth2 = (provider) => {
  console.log(`使用 ${provider} 进行 OAuth2 登录`);
};
</script>
<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-size: cover;
  background-image: url("https://img.neptech.net/i/2025/06/17/iiwdzv.webp");
}

.login-card {
  width: 400px;
  height: 450px;
  margin: auto;
  position: relative;
}

.login-content {
  margin: auto;
  width: 90%;
}

.login-type-switch {
  margin-top: 20px;
  position: absolute;
  bottom: 40px;
  left: 40px;
}

.oauth2-provider-button {
  width: 80px;
  height: 80px;
  border-radius: 20%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.oauth2-provider-button.qq {
  background-image: url("https://img.neptech.net/i/2025/06/17/i85yya.webp"); /* 替换为实际的QQ Logo路径 */
  background-size: cover;
}

.oauth2-provider-button.wechat {
  background-image: url("https://img.neptech.net/i/2025/06/17/i860e7.webp"); /* 替换为实际的微信Logo路径 */
  background-size: cover;
}
</style>
